﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Threading.Tasks;

namespace Hu.Smart.Core.Storage
{
    public class TempFileCacheManager : ITempFileCacheManager
    {
        const string TempFileCacheName = "CacheName__TempFile";

        readonly IMemoryCache _cacheManager;

        public TempFileCacheManager(IMemoryCache cacheManager)
        {
            _cacheManager = cacheManager;
        }

        public void SetFile(string token, byte[] content)
        {
             _cacheManager.GetOrCreate(TempFileCacheName + token, async entry =>
            {
                // 这里可以使用异步~~
                entry.SlidingExpiration = TimeSpan.FromSeconds(60);  // 滑动缓存时间
                return content;
            });
            //_cacheManager.GetCache(TempFileCacheName).Set(token, content, new TimeSpan(0, 0, 1, 0));
        }

        public byte[] GetFile(string token)
        {
            Task<byte[]> result = _cacheManager.Get(token) as Task<byte[]>;
            return result.Result;
            //return _cacheManager.GetCache(TempFileCacheName).Get(token, ep => ep) as byte[];
        }

        public async Task<string> GetDatetimeCache(string token)
        {
            return await _cacheManager.GetOrCreateAsync(TempFileCacheName + token, async entry =>
            {
                // 这里可以使用异步~~
                entry.SlidingExpiration = TimeSpan.FromSeconds(60);  // 滑动缓存时间
                return token + ""+ DateTime.Now.ToString();
            });
            //return _cacheManager.GetCache(TempFileCacheName).Get(token, ep => ep) as byte[];
        }

        public async Task<string> GetStringCache(string token)
        {
            return _cacheManager.Get(TempFileCacheName + token) as string;
            //return _cacheManager.GetCache(TempFileCacheName).Get(token, ep => ep) as byte[];
        }
    }
}